package ru.voice2blog.uploader.amazons3;

import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.voice2blog.common.V2BServiceAdapter;
import ru.voice2blog.common.exception.InitException;
import ru.voice2blog.common.uploader.DataUploader;
import ru.voice2blog.common.uploader.UploadResult;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.Properties;


/**
 * User: ilya.ufo
 * Date: 13.03.11
 * Time: 11:44
 */
public class AmazonS3Uploader extends V2BServiceAdapter implements DataUploader {

    private static final Logger log = LoggerFactory.getLogger(AmazonS3Uploader.class);

    private String bucketName;
    private AmazonS3 s3;


    public UploadResult upload(File file) {
        log.info("Start uploading {}", file.getName());
        String key = file.getName();
        PutObjectResult result = s3.putObject(new PutObjectRequest(bucketName, key, file).withCannedAcl(CannedAccessControlList.PublicRead));
        URL url = s3.generatePresignedUrl(bucketName, key, new Date());

        return new UploadResult(true, url.getProtocol() + "://" + url.getAuthority() + url.getPath());
    }

    @Override
    public void init(Properties properties) throws InitException {
        String accessKey = properties.getProperty("accessKey");
        String secreteKey = properties.getProperty("secreteKey");
        bucketName = properties.getProperty("bucketName");

        s3 = new AmazonS3Client(new BasicAWSCredentials(accessKey, secreteKey));
        try {
            s3.createBucket(bucketName);
            s3.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        } catch (AmazonClientException e) {
            throw new InitException("Error while creating bucket", e);
        }
    }

}
